package com.github.caiqy.shirodemo.config;

import com.github.caiqy.shirodemo.constant.CommonConst;
import com.github.caiqy.shirodemo.db.mapping.Role;
import com.github.caiqy.shirodemo.db.mapping.RolePerm;
import com.github.caiqy.shirodemo.db.mapping.User;
import com.github.caiqy.shirodemo.db.service.RolePermService;
import com.github.caiqy.shirodemo.db.service.RoleService;
import com.github.caiqy.shirodemo.db.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Component("authorizer")
public class CustomRealm extends AuthorizingRealm {

    private UserService userService;

    private RoleService roleService;

    private RolePermService rolePermService;


    @Autowired
    public CustomRealm(UserService userService, RoleService roleService, RolePermService rolePermService) {
        this.userService = userService;
        this.roleService = roleService;
        this.rolePermService = rolePermService;

        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("md5");
        matcher.setStoredCredentialsHexEncoded(true);
        matcher.setHashIterations(1);
        this.setCredentialsMatcher(matcher);
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        if (principalCollection == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }

        User user = (User) getAvailablePrincipal(principalCollection);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(user.getRoles());
        info.setStringPermissions(user.getPerms());
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取用户名之后就是一些登录的判断了
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;

        // 获取登录名
        String loginName = usernamePasswordToken.getUsername();
        // 数据库中获取人员对象
        User user = userService.selectBy("userName", loginName);
        if (user == null) {
            return null;
        }

        // 查询出用户的相关角色 权限 信息
        List<Role> roles = roleService.selectRoleByUserId(user.getId());
        List<RolePerm> rolePerms = CollectionUtils.isEmpty(roles) ? null : rolePermService.selectListIn("roleId", roles.stream().map(Role::getId).collect(Collectors.toSet()));
        user.setRoles(CollectionUtils.isEmpty(roles) ? null : roles.stream().map(Role::getName).collect(Collectors.toSet()));
        user.setPerms(CollectionUtils.isEmpty(rolePerms) ? null : rolePerms.stream().map(RolePerm::getPerm).collect(Collectors.toSet()));

        return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(CommonConst.SALT), this.getName());
    }

}
